package com.duam.serveradmin;

import java.io.IOException;
import java.io.InputStream;

import android.util.Log;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class Exec 
{
	private String host;
	private String user;
	private UserInfo ui;
	private String cmd;
	
	public Exec(String host, String user, UserInfo ui, String cmd)
	{
		this.host = host;
		this.user = user;
		this.ui = ui;
		this.cmd = cmd;
	}

	public String perform() throws InterruptedException, JSchException, IOException
	{
		String response = null;
		
    	JSch jsch = new JSch();
	    	
    	Session session = jsch.getSession(user, host);
        session.setUserInfo(ui);
        session.connect();
	        
    	Channel channel=session.openChannel("exec");
		((ChannelExec)channel).setCommand(cmd);

		channel.setInputStream(null);
		((ChannelExec)channel).setErrStream(System.err);

		InputStream in = channel.getInputStream();
		channel.connect();

		byte[] tmp = new byte[1024];
		
		while(true)
		{
			while(in.available()>0)
			{
				int i=in.read(tmp, 0, 1024);
				if(i<0)break;
				
				response = new String(tmp, 0, i);
				Log.d(getClass().getName(), response);
			}
			
			if(channel.isClosed())
			{
				Log.d(getClass().getName(), "exit-status: "+channel.getExitStatus());
				break;
			}

			Thread.sleep(1000);
		}
		
		channel.disconnect();
		session.disconnect();
		
		return response;
	}
	
}
